import { defineStore } from 'pinia'
import { login } from '@/api/user'
import type { loginForm, loginResponseData } from '@/api/user/type'
import { routeMap, asyncRouteMaps, anyRouteMaps } from '@/router/map'
import { ref } from 'vue'
import { getUserInfo, reqLogut } from '@/api/user'
import router from '@/router'

// @ts-expect-error 忽略js文件对ts的类型校验
import { cloneDeep } from 'lodash'

export const useUserStore = defineStore(
  'users',
  () => {
    let token = ref()
    let menuRoutes = ref()
    let username = ref()
    let avatar = ref()
    let storageMenu = ref<any>([])
    let activeMenu = ref('Home')
    // 登录
    const userLogin = async (data: loginForm) => {
      let res: loginResponseData = await login(data)
      if (res.code === 200) {
        token.value = res.data
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    }
    // 获取用户信息
    const getUserInfoMethod = async () => {
      let res: any = await getUserInfo()
      if (res.code === 200) {
        username.value = res.data.name
        avatar.value = res.data.avatar
        // 获取动态路由
        let userAsyncRoutes = filterAsyncRoutes(
          cloneDeep(asyncRouteMaps),
          res.data.routes
        )
        menuRoutes.value = [...routeMap, ...userAsyncRoutes, anyRouteMaps]
        ;[...userAsyncRoutes, anyRouteMaps].forEach((item: any) => {
          router.addRoute(item)
        })
      }
    }
    // 退出登录
    const userLogout = async () => {
      let res: any = await reqLogut()
      if (res.code === 200) {
        username.value = null
        avatar.value = null
        token.value = null
        // localStorage.removeItem('users')
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    }
    // 过滤用户路由数据
    const filterAsyncRoutes = (asyncRoutes: any, routes: any) => {
      return asyncRoutes.filter((item: any) => {
        if (routes.includes(item.name)) {
          if (item.children && item.children.length > 0) {
            item.children = filterAsyncRoutes(item.children, routes)
          }
          return true
        }
      })
    }

    return {
      token,
      menuRoutes,
      username,
      avatar,
      storageMenu,
      activeMenu,
      userLogin,
      getUserInfoMethod,
      userLogout
    }
  },
  {
    persist: true
  }
)
